import React, { useEffect, useRef, useState, useCallback } from 'react';
import classNames from 'classnames';
import bem from '@/utils/bem';
import './menu.scss';
import { useMenu, OptionItem, MenuItemProps } from './context';
import { useClickAway } from '@/utils';

const defaultProps = {
    disabled: false,
    itemIndex: 0,
    showItem: false,
    options: [],
    onChange: (v: OptionItem) => undefined
}

const MenuItem: React.FC<MenuItemProps> = (props) => {
    const {
        updateTitle,
        hideMenuHandler
    } = useMenu();

    const {
        itemIndex,
        options,
        showItem,
        onChange,
        ...rest
    } = {
        ...defaultProps,
        ...props,
    };



    const b = bem('menu');

    const micRef = useRef<HTMLDivElement>(null) as React.MutableRefObject<HTMLDivElement>;
    const [isOpen, setIsOpen] = useState<boolean>(showItem);

    const [selectedOptionIndex, setSelectedOptionIndex] = useState<number>(0);

    const [position, setPosition] = useState<{ top: number, display: string }>({
        top: 0, display: 'none'
    });

    // 点击外部隐藏菜单
    useClickAway(
        () => {
            console.log('click away');
            hideMenuHandler?.(itemIndex);
        },
        [micRef.current],
        'click',
        false,
        isOpen,
        true
    )

    // 点击菜单子项
    const handleItemClick = (optionIndex: number) => {
        setSelectedOptionIndex(optionIndex);

        if (options[optionIndex]) {
            // 更新menu标题
            updateTitle?.(itemIndex, options[optionIndex].text);
            // 隐藏遮障层
            hideMenuHandler?.(itemIndex);
            // 触发回调函数
            onChange?.(options[optionIndex]);
        }
    }


    // 使用 useCallback 缓存 getPosition 函数
    const getPosition = useCallback(() => {
        if (micRef.current) {
            const bottom = micRef.current.getBoundingClientRect().bottom;
            setPosition({
                top: bottom ? bottom : 0,
                display: isOpen ? 'block' : 'none'
            });
        }
    }, [isOpen]);

    const getActiveClass = (optionIndex: number) => {
        return classNames(b('content__item'), {
            'seal-menu__content__item-active': selectedOptionIndex === optionIndex
        });
    }

    const handleOverlay = useCallback((currentIndex: number) => {
        hideMenuHandler?.(currentIndex);
    }, [hideMenuHandler])

    useEffect(() => {
        getPosition();
        setIsOpen(showItem);
    }, [showItem, getPosition]); // getPosition 现在是稳定的引用

    // 属性是否为空
    if (!options || options.length <= 0) {
        return (<></>);
    }
    return (
        <>
            <div className={b('container')} ref={micRef} >
                <div className='seal-overlay seal-menu-overlay' style={position} onClick={() => handleOverlay(itemIndex)}></div>
                <div className={b('container__main')} style={{ display: isOpen ? 'block' : 'none' }}>
                    <div className={b('content')}>
                        {
                            options?.map((item, optionIndex) => {
                                return (
                                    <div
                                        key={optionIndex}
                                        className={getActiveClass(optionIndex)}
                                        onClick={() => handleItemClick(optionIndex)} >
                                        {item.text}
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </div>
        </>
    )
}

export default MenuItem;